//
//  EditAddressController.m
//  EasyToTesco2.0
//
//  Created by 杨森 on 16/7/27.
//  Copyright © 2016年 EasyToTesco. All rights reserved.
//

#import "EditAddressController.h"
#import "CreatAddCell.h"
#import "TextFieldCell.h"
#import "GPDateView.h"

#define Key_DistrictSelectProvince          @"DistrictSelectProvince"
#define Key_DistrictSelectProvinceCode      @"DistrictSelectProvinceCode"
#define Key_DistrictSelectProvinceSubCode   @"DistrictSelectProvinceSubCode"
#define Key_DistrictSelectProvinceSub       @"DistrictSelectProvinceSub"
#define Key_DistrictSelectCityCode          @"DistrictSelectCityCode"
#define Key_DistrictSelectCity              @"DistrictSelectCity"

@interface EditAddressController ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate>
{
    UITextField *phoneNumTextField;
    UITextField *nameTextField;
    UITextField *postCodeTextField;
    UITextField *detailAddressField;
}

@property (nonatomic, strong) UITableView *editAddressView;

//省市区
@property (nonatomic, strong) NSString *province;
@property (nonatomic, strong) NSString *city;
@property (nonatomic, strong) NSString *countory;

//
@property (nonatomic, strong) NSString *name;
@property (nonatomic, strong) NSString *phoneNum;
@property (nonatomic, strong) NSString *postCode;
@property (nonatomic, strong) NSString *detailAddress;


@end

@implementation EditAddressController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"修改地址";
    
//    NSLog(@"%@",self.addressModel);
    
    _name = _addressModel.name;
    _postCode = _addressModel.postcode;
    _phoneNum = _addressModel.phone;
    _detailAddress = _addressModel.address;
    _province = _addressModel.province;
    _city = _addressModel.city;
    _countory = _addressModel.county;
    
    [self setupUI];
}

- (void)setupUI
{
    [self.view addSubview:self.editAddressView];
    self.editAddressView.delegate = self;
    self.editAddressView.dataSource = self;
    [self.editAddressView registerNib:[UINib nibWithNibName:@"TextFieldCell" bundle:nil] forCellReuseIdentifier:@"TextFieldCell"];
    [self.editAddressView registerNib:[UINib nibWithNibName:@"CreatAddCell" bundle:nil] forCellReuseIdentifier:@"CreatAddCell"];
    //默认名字弹起
    [nameTextField becomeFirstResponder];
    
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem barButtonItemWithImage:nil highImage:nil target:self action:@selector(editUserAddressMessage) forControlEvents:UIControlEventTouchUpInside title:@"保存"];
    
    //监听键盘的弹出
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardFrameChange:) name:UIKeyboardWillChangeFrameNotification object:nil];
}

//保存点击
- (void)editUserAddressMessage
{
    [self textFieldResignFirstResponder];
    
//    NSLog(@"%@",_name);
//    NSLog(@"%@",_phoneNum);
//    NSLog(@"%@",_postCode);
//    NSLog(@"%@",_detailAddress);
    
    //判断参数是否为空
    if (_name.length && _detailAddress.length && _postCode.length &&_phoneNum.length && self.province.length) {
        //新增地址请求
        [self editAddressRequestData];
    }else{
        //提示框
        MBProgressHUD *hud = [MBProgressHUD showMessage:@"请填写完整信息" toView:self.view dimBackground:false AndCompleteBlock:^(id object) {
            NSLog(@"完成");
        }];
        [self.view addSubview:hud];
        
    }

    
}

- (void)editAddressRequestData
{
    
    //用户名
    NSDictionary *params = @{@"username":[NSString stringWithFormat:@"%@", USERNAME],
                             //收货姓名
                             @"name":[NSString stringWithFormat:@"%@",_name],
                             //手机
                             @"phone":[NSString stringWithFormat:@"%@",_phoneNum],
                             //完整地址
                             @"address":[NSString stringWithFormat:@"%@",_detailAddress],
                             //是否启用
                             @"zt":[NSString stringWithFormat:@"%d",0],
                             //邮编
                             @"postcode":[NSString stringWithFormat:@"%@",_postCode],
                             //省份
                             @"province":[NSString stringWithFormat:@"%@",_province],
                             //城市
                             @"city":[NSString stringWithFormat:@"%@",_city],
                             //地区
                             @"county":[NSString stringWithFormat:@"%@",_countory],
                             //地址id
                             @"address_id":[NSString stringWithFormat:@"%d",_addressModel.re_id]
                             };
    
    [[NetWorkSharedTools sharedNetWorkTools] GetObjectWithURLDict:params AndMenthodName:@"/api/User/editAddress" completeBlock:^(id object) {
        if (JudgeBackDataCode) {
            //提示框
            MBProgressHUD *hud = [MBProgressHUD showMessage:@"修改地址成功" toView:self.view dimBackground:false AndCompleteBlock:^(id object) {
                [self.navigationController popViewControllerAnimated:YES];
            }];
            [self.view addSubview:hud];
        }
        
    }];
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    if ([textField isEqual:nameTextField]) {
        _name = nameTextField.text;
        NSLog(@"nameTextField = %@",_name);
    }else if ([textField isEqual:phoneNumTextField]){
        _phoneNum = phoneNumTextField.text;
        NSLog(@"phoneNumTextField = %@",_phoneNum);
    }else if ([textField isEqual:postCodeTextField]){
        _postCode = postCodeTextField.text;
        NSLog(@"postCodeTextField = %@",_postCode);
    }else{
        _detailAddress = detailAddressField.text;
        NSLog(@"detailAddressField = %@",_detailAddress);
    }
}

#pragma mark - 键盘的Frame改变的时候调用
- (void)keyboardFrameChange:(NSNotification *)note {
    
    CGFloat durtion = [note.userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue];
    //获取键盘的frame
    CGRect frame = [note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    
    if (frame.origin.y == HEIGHT) {//没有弹出键盘
        [UIView animateWithDuration:durtion animations:^{
            self.editAddressView.Height = HEIGHT;
        }];
    } else {//弹出键盘
        [UIView animateWithDuration:durtion animations:^{
            //工具条往上移动271
            self.editAddressView.Height = HEIGHT - frame.size.height;
        }];
    }
}

#pragma mark UITableView DataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 5;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"editCell"];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"editCell"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.textLabel.font = [UIFont systemFontOfSize:13];
    }
    if (indexPath.section == 0) {
        if (indexPath.row < 3) {
            TextFieldCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TextFieldCell" forIndexPath:indexPath];
            cell.TextField.delegate = self;
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            if (indexPath.row == 1) {
                cell.TextField.text = _addressModel.phone;
                phoneNumTextField = cell.TextField;
                cell.TextField.keyboardType = UIKeyboardTypeNumberPad;
                
            }
            if (indexPath.row == 0) {
                cell.TextLabel.text = @"收货人";
                cell.TextField.text = _addressModel.name;
                nameTextField = cell.TextField;
            }
            if (indexPath.row == 2) {
                cell.TextLabel.text = @"邮编";
                cell.TextField.text = _addressModel.postcode;
                postCodeTextField = cell.TextField;
                cell.TextField.keyboardType = UIKeyboardTypeNumberPad;
            }
            
            return cell;
        } else if (indexPath.row == 3) {
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            cell.textLabel.text = @"所在地区";
            cell.detailTextLabel.text = [NSString stringWithFormat:@"%@%@%@",_addressModel.province,_addressModel.city,_addressModel.county];
            
        } else {
            CreatAddCell*cell = [tableView dequeueReusableCellWithIdentifier:@"CreatAddCell" forIndexPath:indexPath];
            cell.TextField.delegate = self;
            cell.TextField.text = _addressModel.address;
            detailAddressField = cell.TextField;
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            
            return cell;
        }
    }
    
    return cell;
}

#pragma mark - UITableView Delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == 0) {
        if (indexPath.row == 3) {
            [self textFieldResignFirstResponder];
            [self pickerView:indexPath];
        }
    }
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        if (indexPath.row == 4) {
            return 120;
        }
    }
    return 50;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.01;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 20;
}


- (void)pickerView:(NSIndexPath *)indexPath{
    
    GPDateView * dateView = [[GPDateView alloc] initWithFrame:CGRectMake(0, HEIGHT-250, WIDTH, 250) Data:nil];
    
    [dateView showPickerView];
    
    dateView.ActionDistrictViewSelectBlock = ^(NSString *desStr,NSDictionary *selectDistrictDict){
        UITableViewCell *cell = [self.editAddressView cellForRowAtIndexPath:indexPath];
        cell.detailTextLabel.text = [NSString stringWithFormat:@"%@%@%@", [selectDistrictDict objectForKey:Key_DistrictSelectProvince], [selectDistrictDict objectForKey:Key_DistrictSelectCity], [selectDistrictDict objectForKey:Key_DistrictSelectProvinceSub]];
        
        self.province = [selectDistrictDict objectForKey:Key_DistrictSelectProvince];
        self.city = [selectDistrictDict objectForKey:Key_DistrictSelectCity];
        self.countory = [selectDistrictDict objectForKey:Key_DistrictSelectProvinceSub];
        
    };
}

- (void)textFieldResignFirstResponder {
    
    [nameTextField resignFirstResponder];
    [phoneNumTextField resignFirstResponder];
    [postCodeTextField resignFirstResponder];
    [detailAddressField resignFirstResponder];
}

- (UITableView *)editAddressView {
    if (!_editAddressView) {
        _editAddressView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT) style:UITableViewStyleGrouped];
    }
    return _editAddressView;
}

@end
